package com.music.common.entity;


import java.util.StringTokenizer;


/**
 * Data type which can be included as a request attribute
 */
public class Email {
    
    /** MAX length of emails */
    public static final short MAX_EMAIL_LENGTH = 90;

    /**
     * This address
     */
    private String address;
    
    private Email() {
        super();
    }
    

    /**
     * Construct a valid Email address
     *
     * @param address The email address
     */
    public Email(String address) throws IllegalArgumentException {
        super();
        if (Email.isEmailAddressValid(address) == false) {
            throw new IllegalArgumentException();
        }
        this.address = address.toLowerCase();
    }

    public String getAddress() {
        return address.toLowerCase();
    }
    
    public Email deepCopy() {
        Email email = new Email(this.address);
        return email;
    }
    
    public static boolean isEmailAddressValid(String emailAddress) {
        
        if (emailAddress == null) {
            return false;
        }
        
        if (emailAddress.length() > MAX_EMAIL_LENGTH) {
            return false;
        } 
        
        emailAddress = emailAddress.trim();

        // tokenizing the . might miss a trailing one
        if (emailAddress.toCharArray()[emailAddress.length() - 1] == '.') {
            return false;
        }

        StringTokenizer add = new StringTokenizer(emailAddress, "@");

        if (add.countTokens() != 2) {
            return false;
        }

        for (int i = 0; i < 2; i++) {
            String token = add.nextToken();
            if (i == 1) {
                StringTokenizer dom = new StringTokenizer(token, ".");
                if (dom.countTokens() <= 1) {
                    return false;
                }
            }
        }  
        return true;
    }
    
    /**
     * @see java.lang.Object#hashCode()
     */
    public int hashCode() {

        int result = 17;
        result = 37 * result + address.hashCode();
        return result;
    }

    
    public boolean equals(Object obj) {
        if (!(obj instanceof Email)) {
            return false;
        }
        Email email = (Email)obj;
        return (this.address.equals(email.address));
    }
}
